<script>
export default {
  name: 'addOrEditRoleDialog',
  props: {
    showRoleDialog: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      /* 表单数据对象 */
      formData: {
        name: '',
        description: ''
      },
      /* 表单规则对象 */
      formRules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    /* 用于派发action发送请求获取部门详情的回调函数 */
    async findRole(id) {
      try {
        const role = await this.$store.dispatch('settingsStore/findRole', id)
        this.formData = role
      } catch (error) {
        this.$message.error(error.message)
      }
    },
    /* 用于派发action发送请求添加部门的回调函数 */
    async addRole() {
      try {
        const message = await this.$store.dispatch('settingsStore/addRole', this.formData)
        this.$message.success(message)
        this.$emit('submit')
      } catch (error) {
        this.$message.error(error.message)
      }
    },
    /* 用于派发action发送请求修改部门的回调函数 */
    async editRole() {
      try {
        const message = await this.$store.dispatch('settingsStore/updateRole', this.formData)
        this.$message.success(message)
        this.$emit('submit')
      } catch (error) {
        this.$message.error(error.message)
      }
    },

    /* 用于清空表单残留数据和重置表单的回调函数 */
    clearFormData() {
      this.formData = { name: '', description: '' }
      this.$refs.elForm.resetFields()
    },
    /* 对话框关闭时的回调函数 */
    handleClose() {
      this.clearFormData()
      this.$emit('update:showRoleDialog', false)
    },
    /* 点击取消按钮的回调函数 */
    handleCancel() {
      this.$emit('update:showRoleDialog', false)
    },
    /* 点击确定按钮的回调函数 */
    async handleSubmit() {
      const valid = await this.$refs.elForm.validate().catch(error => error)
      if (!valid) return
      if (this.formData.id) {
        // 编辑操作
        this.editRole()
      } else {
        // 添加操作
        this.addRole()
      }
    }
  },
  computed: {
    title() {
      return this.formData.id ? '编辑角色' : '新增角色'
    }
  },
  emits: ['submit']
}
</script>

<template>
  <el-dialog :title="title" :visible="showRoleDialog" @close="handleClose" :close-on-click-modal="false">
    <el-form label-width="100px" :model="formData" :rules="formRules" ref="elForm">
      <el-form-item label="角色名称" prop="name">
        <el-input placeholder="请输入角色名称" v-model="formData.name"></el-input>
      </el-form-item>
      <el-form-item label="角色描述" prop="description">
        <el-input placeholder="请输入角色描述" type="textarea" rows="5" resize="none" v-model="formData.description"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="danger" @click="handleCancel">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<style scoped lang="scss">

</style>
